<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width="500" height="500"></canvas>
  <script>
    const dpr = window.devicePixelRatio || 1;
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = canvas.clientWidth * dpr;
    canvas.height = canvas.clientHeight * dpr;
    ctx.scale(dpr, dpr);

    let mouseX = 0;
    let mouseY = 0;
    let currentZIndex = 1; // 用于动态调整 zIndex

    const squares = [
      { x: 100, y: 100, size: 100, color: 'red', isDragging: false, zIndex: 1 },
      { x: 300, y: 300, size: 100, color: 'blue', isDragging: false, zIndex: 2 },
    ];

    let offsetX = 0;
    let offsetY = 0;

    // 绘制所有方块
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布

      // 按 zIndex 排序后绘制方块
      squares
        .sort((a, b) => a.zIndex - b.zIndex)
        .forEach(square => {
          ctx.fillStyle = square.color;
          ctx.fillRect(square.x, square.y, square.size, square.size);
        });
    }

    // 检查鼠标是否在方块内
    function isMouseInSquare(mouseX, mouseY, square) {
      return (
        mouseX >= square.x &&
        mouseX <= square.x + square.size &&
        mouseY >= square.y &&
        mouseY <= square.y + square.size
      );
    }

    // 鼠标按下事件
    canvas.addEventListener('mousedown', (event) => {
      const rect = canvas.getBoundingClientRect();
      const mouseX = event.clientX - rect.left;
      const mouseY = event.clientY - rect.top;

      squares.forEach(square => {
        if (isMouseInSquare(mouseX, mouseY, square)) {
          square.isDragging = true;
          offsetX = mouseX - square.x;
          offsetY = mouseY - square.y;

          // 更新 zIndex，使当前方块显示在最上层
          currentZIndex++;
          square.zIndex = currentZIndex;
        }
      });

      draw();
    });

    // 鼠标移动事件
    canvas.addEventListener('mousemove', (event) => {
      const rect = canvas.getBoundingClientRect();
      const mouseX = event.clientX - rect.left;
      const mouseY = event.clientY - rect.top;

      squares.forEach(square => {
        if (square.isDragging) {
          square.x = mouseX - offsetX;
          square.y = mouseY - offsetY;
          draw();
        }
      });
    });

    // 鼠标释放事件
    canvas.addEventListener('mouseup', () => {
      squares.forEach(square => {
        square.isDragging = false;
      });
    });

    // 初始绘制
    draw();
  </script>
</body>
</html>